/**
 * 
 */
package com.whf15.o2o.web.shopadmin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.omg.PortableServer.REQUEST_PROCESSING_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.whf15.o2o.dto.ImageHolder;
import com.whf15.o2o.dto.ShopExecution;
import com.whf15.o2o.entity.Area;
import com.whf15.o2o.entity.PersonInfo;
import com.whf15.o2o.entity.Shop;
import com.whf15.o2o.entity.ShopCategory;
import com.whf15.o2o.enums.ShopStateEnum;
import com.whf15.o2o.exceptions.ShopOperationException;
import com.whf15.o2o.service.AreaService;
import com.whf15.o2o.service.ShopCategoryService;
import com.whf15.o2o.service.ShopService;
import com.whf15.o2o.util.CodeUtil;
import com.whf15.o2o.util.HttpServletRequestUtil;
import com.whf15.o2o.util.ImageUtil;
import com.whf15.o2o.util.PathUtil;

/**
 * @author 作者 :whfo
 * @version 创建时间：2021年5月6日 下午8:07:43 类说明
 */
@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {

	@Autowired
	private ShopService shopService;
	@Autowired
	private ShopCategoryService shopCategoryService;
	@Autowired
	private AreaService areaService;
	
	@RequestMapping(value="/getshopmanagementinfo",method=RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopManagementInfo(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<String,Object>();
		long shopId = HttpServletRequestUtil.getLong(request, "shopId");
		//前端没有获取到shopId
		if(shopId <= 0 ) {
			//试着从session中获取
			Object currentShopObj = request.getSession().getAttribute("currentShop");
			//session中还是没有，重定向url
			if(currentShopObj == null){
				modelMap.put("redirect", true);
				modelMap.put("url", "/o2o/shopadmin/shoplist");
			}else {
				Shop currentShop = (Shop) currentShopObj;
				modelMap.put("redirect", false);
				modelMap.put("shopId", currentShop.getShopId());
			}
		}else {
			Shop currentShop = new Shop();
			currentShop.setShopId(shopId);
			request.getSession().setAttribute("currentShop", currentShop);
			modelMap.put("redirect", false);
		}
		return modelMap;
	}
	
	
	@RequestMapping(value="/getshoplist",method=RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopList(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<String, Object>();
		// 确保user是有值的
//		PersonInfo user = new PersonInfo();
//		user.setUserId(8L);
//		user.setUserId(1L);
//		
//		user.setName("whfo");
//		request.getSession().setAttribute("user", user);
//		user = (PersonInfo) request.getSession().getAttribute("user");
		PersonInfo user = (PersonInfo) request.getSession().getAttribute("user");

		//long employeeId = user.getUserId();
		//List <Shop> shopList = new ArrayList<Shop>();
		try {
			Shop shopCondition = new Shop();
			shopCondition.setOwner(user);
			
			//默认一个人创建的店铺100个，从0开始
			ShopExecution se = shopService.getShopList(shopCondition, 0, 100);
			
			modelMap.put("shopList", se.getShopList());
			modelMap.put("user", user);
			modelMap.put("success", true);
			
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
		}
		return modelMap;
		
	}
	
	
	@RequestMapping(value="getshopbyId",method=RequestMethod.GET)
	@ResponseBody
	private Map<String, Object>getShopById(HttpServletRequest request){
		Map<String,Object>modelMap = new HashMap<String,Object>();
		Long shopId = HttpServletRequestUtil.getLong(request, "shopId");
		if(shopId > -1) {
			try {
				Shop shop = shopService.getByShopId(shopId);
				List<Area> areaList = areaService.getAreaList();
				modelMap.put("shop", shop);
				modelMap.put("areaList", areaList);
				modelMap.put("success", true);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
		}else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "empty shopId");
		}
		return modelMap;
		

	}
	

	@RequestMapping(value="getshopinitinfo",method=RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopInitInfo() {

		Map<String, Object> modelMap = new HashMap<String, Object>();
		List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>();
		List<Area> areaList = new ArrayList<Area>();

		try {
			shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory());
			areaList = areaService.getAreaList();
			modelMap.put("shopCategoryList", shopCategoryList);
			modelMap.put("areaList", areaList);
			modelMap.put("success", true);

		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
		}
		return modelMap;

	}

	@RequestMapping(value = "/registershop", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> registerShop(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		
		if(!CodeUtil.checkVerifyCodeActual(request)) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "wdnmd！看清楚点验证码");
			return modelMap;
		}
		
		// 1.接收并转换响应的参数，包括店铺信息以及图片信息
		// 1.1 接收从前端传来的店铺相关的字符串信息，转换位我们所需的shop实体类
		String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
		ObjectMapper mapper = new ObjectMapper();
		Shop shop = null;
		try {
			shop = mapper.readValue(shopStr, Shop.class);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			return modelMap;
		}

		// 1.2接收图片信息
		CommonsMultipartFile shopImg = null;
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());

		if (commonsMultipartResolver.isMultipart(request)) {
			// 是否检测到上传信息流
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "上传图片不能为空");
			return modelMap;
		}

		// 2.注册店铺

		if (shop != null && shopImg != null) {
			PersonInfo owner = (PersonInfo) request.getSession().getAttribute("user");
			shop.setOwner(owner);
			ShopExecution se;
			try {
				ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(), shopImg.getInputStream());
				se = shopService.addShop(shop, imageHolder);

				if (se.getState() == ShopStateEnum.CHECK.getState()) {
					modelMap.put("success", true);
					//用户可以操作的店铺列表
					@SuppressWarnings("unchecked")
					List<Shop>shopList = (List<Shop>) request.getSession().getAttribute("shopList");
					if(shopList==null||shopList.size()==0) {
						shopList = new ArrayList<Shop>();
					}
					shopList.add(se.getShop());
					request.getSession().setAttribute("shopList",shopList);
				} else {
					modelMap.put("success", false);
					modelMap.put("errMsg", se.getStateInfo());
				}
			} catch (ShopOperationException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			} catch (IOException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			}

			return modelMap;
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入店铺信息");
			return modelMap;
		}

		// 3.返回结果

	}

	@RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> modifyShop(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		
		if(!CodeUtil.checkVerifyCodeActual(request)) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "wdnmd！看清楚点验证码");
			return modelMap;
		}
		
		// 1.接收并转换响应的参数，包括店铺信息以及图片信息
		// 1.1 接收从前端传来的店铺相关的字符串信息，转换位我们所需的shop实体类
		String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
		ObjectMapper mapper = new ObjectMapper();
		Shop shop = null;
		try {
			shop = mapper.readValue(shopStr, Shop.class);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			return modelMap;
		}

		// 1.2接收图片信息
		CommonsMultipartFile shopImg = null;
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());

		if (commonsMultipartResolver.isMultipart(request)) {
			// 是否检测到上传信息流
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
		}

		// 2.修改店铺
		if (shop != null && shop.getShopId()!=null) {
			
			ShopExecution se;
			
			try {
				if(shopImg == null) {
					se = shopService.modifyShop(shop, null);
				}else {
					ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(), shopImg.getInputStream());
					se = shopService.modifyShop(shop, imageHolder);

				}

				if (se.getState() == ShopStateEnum.SUCCESS.getState()) {
					modelMap.put("success", true);
				} else {
					modelMap.put("success", false);
					modelMap.put("errMsg", se.getStateInfo());
				}
			} catch (ShopOperationException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			} catch (IOException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			}

			return modelMap;
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入店铺ID");
			return modelMap;
		}

		// 3.返回结果

	}

	// private static void inputStreamToFile(InputStream ins,File file) {
	// FileOutputStream os = null;
	//
	// try {
	// os = new FileOutputStream(file);
	// int bytesRead = 0;
	// byte[] buffer = new byte[1024];
	// while((bytesRead = ins.read(buffer))!=-1) {
	// os.write(buffer,0,bytesRead);
	// }
	// } catch (Exception e) {
	// throw new RuntimeException("调用inputStreamToFile产生异常："+e.getMessage());
	//
	// }finally {
	// try {
	// if(os!=null) os.close();
	// if(ins != null) ins.close();
	//
	// } catch (IOException e2) {
	// throw new RuntimeException("inputStreamToFile关闭io产生异常:"+e2.getMessage());
	// }
	// }
	// }
}
